package com.edu.demo.service.impl;

import com.alibaba.fastjson2.JSON;
import com.edu.demo.pojo.AjaxResult;
import com.edu.demo.utils.ServletUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * @ClassName: AuthenticationEntryPointImpl
 * @Description:
 * @Author: jxw
 * @Date: 2023-01-25
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable
{
    private static final long serialVersionUID = -8970718410437077606L;
    private static final Logger log = LoggerFactory.getLogger(AuthenticationEntryPointImpl.class);

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException
    {
        StringBuilder builder = new StringBuilder("请求访问：");
        log.error(builder.append(request.getRequestURI()).append(",认证失败,").append(e.getMessage()).toString());
        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(401, builder.toString())));
    }
}
